<template>
  <view class="order-list-container">
    <!-- 搜索框 -->
    <view class="search-bar">
      <input 
        class="search-input" 
        type="text" 
        :placeholder="activeTab === 0 ? '输入桌号或订单号搜索' : '在当前状态下搜索桌号'" 
        v-model="searchKeyword"
        @input="onSearchInput"
      />
      <text class="search-icon">🔍</text>
    </view>

    <!-- 状态标签 -->
    <view class="status-tabs">
      <text 
        class="tab-item" 
        :class="{ active: activeTab === index }"
        v-for="(tab, index) in tabs"
        :key="index"
        @click="changeTab(index)"
      >{{ tab }}</text>
    </view>

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list">
      <view class="order-item" v-for="(order, index) in filteredOrders" :key="index" @click="toggleProducts(order)">
        <view class="item-header">
          <text class="item-board-name">{{ order.board_name }}</text>
          <text class="item-category">{{ order.category }}</text>
          <text class="item-status">{{ order.statusText }}</text>
          <view class="expand-hint">
            <text class="hint-text">{{ order.showProducts ? '收起' : '点击查看详情' }}</text>
            <text class="arrow-icon" :class="{ 'expanded': order.showProducts }">▶</text>
          </view>
        </view>

        <view v-if="order.showProducts">
          <view class="product-info" v-for="(product, pIndex) in order.products" :key="pIndex">
            <image class="product-image" :src="product.image" mode="aspectFill"></image>
            <view class="product-details">
              <text class="product-name">{{ product.name }}</text>
              <text class="product-description">{{ product.description }}</text>
            </view>
            <view class="product-quantity-price">
              <text class="product-price">¥{{ product.price.toFixed(2) }}</text>
              <text class="product-quantity">x{{ product.quantity }}</text>
            </view>
          </view>

          <view class="item-summary">
            <text class="summary-text">共{{ order.totalQuantity }}件商品 合计:</text>
            <text class="summary-price">¥{{ order.totalPrice.toFixed(2) }}</text>
            <text class="summary-shipping" v-if="order.shippingCost > 0">(含运费 ¥{{ order.shippingCost.toFixed(2) }})</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { orderApi } from '../../utils/api'
import { ref, onMounted } from 'vue'

export default {
  data() {
    return {
      searchKeyword: '',
      activeTab: 0,
      tabs: ['全部', '待支付', '已支付', '已取消'],
      orders: []
    }
  },
  computed: {
    filteredOrders() {
      let filtered = this.orders

      // 先按状态标签过滤
      if (this.activeTab !== 0) {
        const statusMap = {
          1: 'TO_BE_PAID',
          2: 'PAID',
          3: 'CANCELED'
        }
        filtered = filtered.filter(order => order.status === statusMap[this.activeTab])
      }

      // 再按搜索关键词（桌号）过滤
      if (this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase()
        filtered = filtered.filter(order => {
          if (order.board_name.toLowerCase().includes(keyword)) {
            return true
          }
          if (order.category === '外卖订单' && order.id.toString().includes(keyword)) {
            return true
          }
          return false
        })
      }

      return filtered
    }
  },
  methods: {
    // 切换标签页
    changeTab(index) {
      this.activeTab = index
    },

    // 获取订单列表
    async getOrders() {
      try {
        const res = await orderApi.getRegionOrders([9, 10])
        if (res.code === 200) {
          this.orders = res.data.map(order => ({
            id: order.orderId,
            category: order.orderType === 1 ? '堂食订单' : '外卖订单',
            status: order.orderStatus,
            statusText: this.getOrderStatus(order.orderStatus),
            board_name: order.boardName || '外卖订单',
            place_order_time: new Date(order.placeOrderTime).toLocaleString(),
            total_amount: order.totalAmount,
            discount_amount: order.discountAmount,
            payable_amount: order.payableAmount,
            operator_name: order.operatorName,
            payment_time: order.paymentTime ? new Date(order.paymentTime).toLocaleString() : '',
            remark: order.remark || '',
            shipping_address: order.shippingAddress || '',
            products: [],
            totalQuantity: 0,
            totalPrice: order.totalAmount,
            shippingCost: 0,
            showProducts: false
          }))

          // 逐个获取订单详情
          for (let order of this.orders) {
            try {
              const detailRes = await orderApi.getOrderInfo(order.id)
              if (detailRes.code === 200) {
                const orderItems = detailRes.data
                order.products = orderItems.map(item => ({
                  name: item.dish.dishName,
                  description: item.dish.dishDescribe || '',
                  price: item.dish.price,
                  quantity: item.orderItem.quantity,
                  image: item.dish.dishImage ? `/static/dishes/${item.dish.dishImage}` : '/static/product-placeholder.png'
                }))
                order.totalQuantity = order.products.reduce((sum, item) => sum + item.quantity, 0)
              }
            } catch (error) {
              console.error(`获取订单${order.id}详情失败:`, error)
              continue
            }
          }
        } else {
          uni.showToast({
            title: '获取订单列表失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
        uni.showToast({
          title: '获取订单列表失败',
          icon: 'none'
        })
      }
    },

    // 获取订单状态文本
    getOrderStatus(status) {
      const statusMap = {
        'TO_BE_PAID': '待支付',
        'PAID': '已支付',
        'CANCELED': '已取消'
      }
      return statusMap[status] || '未知状态'
    },

    // 切换菜品显示状态
    toggleProducts(order) {
      order.showProducts = !order.showProducts
    },

    // 搜索输入处理
    onSearchInput(e) {
      this.searchKeyword = e.detail.value
    }
  },
  onMounted() {
    this.getOrders()
  },
  onLoad() {
    this.getOrders()
  },
  onShow() {
    this.refreshOrderStatus()
  }
}
</script>

<style lang="scss" scoped>
.order-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #C70209;
  flex-wrap: nowrap;
  overflow: hidden;
  min-height: 100rpx;

  .search-input {
    flex: 1;
    height: 70rpx;
    background-color: #ffffff;
    border-radius: 35rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
    margin-right: 15rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    box-sizing: border-box;
    line-height: 70rpx;
  }

  .search-icon {
    color: #ffffff;
    font-size: 40rpx;
    flex-shrink: 0;
    padding: 10rpx;
  }
}

.status-tabs {
  display: flex;
  justify-content: space-around;
  background-color: #ffffff;
  border-bottom: 1px solid #eee;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;

    &.active {
      color: #C70209;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background-color: #C70209;
      }
    }
  }
}

.order-list {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
}

.order-item {
  background-color: #ffffff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;

  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15rpx;
    padding-bottom: 10rpx;
    border-bottom: 1px solid #eee;
    position: relative;
    flex-wrap: wrap;

    .item-board-name {
      font-size: 26rpx;
      color: #333;
      font-weight: bold;
      flex-basis: 100%;
      margin-bottom: 5rpx;
      text-align: left;
    }

    .item-category {
      font-size: 26rpx;
      color: #666;
      margin-right: auto;
    }

    .item-status {
      font-size: 26rpx;
      color: #C70209;
    }

    .expand-hint {
      display: flex;
      align-items: center;
      margin-left: auto;

      .hint-text {
        font-size: 24rpx;
        color: #999;
        margin-right: 10rpx;
      }

      .arrow-icon {
        font-size: 20rpx;
        color: #999;
        transition: transform 0.3s ease;

        &.expanded {
          transform: rotate(90deg);
        }
      }
    }
  }

  .product-info {
    display: flex;
    align-items: center;
    margin-bottom: 15rpx;
    width: 100%;
    overflow: hidden;
    flex-wrap: nowrap;
    box-sizing: border-box;

    .product-image {
      width: 120rpx;
      height: 120rpx;
      background-color: #eee;
      margin-right: 15rpx;
      flex-shrink: 0;
    }

    .product-details {
      flex: 1;
      min-width: 0;
      margin-right: 15rpx;
      overflow: hidden;
      box-sizing: border-box;

      .product-name {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 4rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 100%;
      }

      .product-description {
        font-size: 24rpx;
        color: #999;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 100%;
      }
    }

    .product-quantity-price {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      flex-shrink: 0;
      white-space: nowrap;
      margin-left: 10rpx;
      box-sizing: border-box;

      .product-price {
        font-size: 28rpx;
        color: #C70209;
        font-weight: bold;
        margin-bottom: 4rpx;
      }

      .product-quantity {
        font-size: 24rpx;
        color: #666;
      }
    }
  }

  .item-summary {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 15rpx;
    padding-top: 10rpx;
    border-top: 1px solid #eee;
    flex-wrap: wrap;

    .summary-text {
      font-size: 26rpx;
      color: #333;
      margin-right: 10rpx;
    }

    .summary-price {
      font-size: 30rpx;
      color: #C70209;
      font-weight: bold;
      margin-left: 10rpx;
    }

    .summary-shipping {
      font-size: 22rpx;
      color: #999;
      margin-left: 10rpx;
    }
  }
}
</style>
